<template>
  <div class="approval-start-container">
    <el-card>
      <div slot="header">
        <span>发起审批 - {{ process.processName }}</span>
        <el-tag v-if="!hasPermission" type="danger" size="small" style="margin-left: 10px;">
          无权限发起
        </el-tag>
      </div>
      
      <el-form ref="approvalForm" :model="approvalForm" :rules="approvalRules" label-width="120px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="approvalForm.title" placeholder="请输入审批标题" />
        </el-form-item>
        
        <!-- 动态表单字段 -->
        <template v-if="formFields.length > 0">
          <el-form-item
            v-for="field in formFields"
            :key="field.name"
            :label="field.label"
            :prop="'formData.' + field.name"
            :rules="field.required ? [{ required: true, message: '请填写' + field.label, trigger: 'blur' }] : []"
          >
            <!-- 单行文本 -->
            <el-input
              v-if="field.type === 'input'"
              v-model="approvalForm.formData[field.name]"
              :placeholder="field.placeholder"
            />
            
            <!-- 多行文本 -->
            <el-input
              v-if="field.type === 'textarea'"
              v-model="approvalForm.formData[field.name]"
              type="textarea"
              :rows="field.rows || 3"
              :placeholder="field.placeholder"
            />
            
            <!-- 数字输入 -->
            <el-input-number
              v-if="field.type === 'number'"
              v-model="approvalForm.formData[field.name]"
              :min="field.min"
              :max="field.max"
              :step="field.step || 1"
              style="width: 100%;"
            />
            
            <!-- 下拉选择 -->
            <el-select
              v-if="field.type === 'select'"
              v-model="approvalForm.formData[field.name]"
              :placeholder="field.placeholder"
              style="width: 100%;"
            >
              <el-option
                v-for="option in field.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            
            <!-- 单选框 -->
            <el-radio-group
              v-if="field.type === 'radio'"
              v-model="approvalForm.formData[field.name]"
            >
              <el-radio
                v-for="option in field.options"
                :key="option.value"
                :label="option.value"
              >{{ option.label }}</el-radio>
            </el-radio-group>
            
            <!-- 多选框 -->
            <el-checkbox-group
              v-if="field.type === 'checkbox'"
              v-model="approvalForm.formData[field.name]"
            >
              <el-checkbox
                v-for="option in field.options"
                :key="option.value"
                :label="option.value"
              >{{ option.label }}</el-checkbox>
            </el-checkbox-group>
            
            <!-- 日期选择 -->
            <el-date-picker
              v-if="field.type === 'date'"
              v-model="approvalForm.formData[field.name]"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="field.placeholder"
              style="width: 100%;"
            />
            
            <!-- 时间选择 -->
            <el-time-picker
              v-if="field.type === 'time'"
              v-model="approvalForm.formData[field.name]"
              value-format="HH:mm:ss"
              :placeholder="field.placeholder"
              style="width: 100%;"
            />
            
            <!-- 日期范围 -->
            <el-date-picker
              v-if="field.type === 'daterange'"
              v-model="approvalForm.formData[field.name]"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%;"
            />
            
            <!-- 开关 -->
            <el-switch
              v-if="field.type === 'switch'"
              v-model="approvalForm.formData[field.name]"
            />
            
            <!-- 评分 -->
            <el-rate
              v-if="field.type === 'rate'"
              v-model="approvalForm.formData[field.name]"
            />
            
            <!-- 滑块 -->
            <el-slider
              v-if="field.type === 'slider'"
              v-model="approvalForm.formData[field.name]"
              :min="field.min || 0"
              :max="field.max || 100"
            />
          </el-form-item>
        </template>
        
        <!-- 无表单字段提示 -->
        <el-alert
          v-if="formFields.length === 0"
          title="该流程暂未配置表单字段"
          type="warning"
          :closable="false"
          show-icon
        />
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="submitting" 
            :disabled="!hasPermission"
            @click="handleSubmit"
          >
            提交审批
          </el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
        
        <!-- 权限提示 -->
        <el-alert
          v-if="!hasPermission"
          :title="permissionMessage"
          type="error"
          :closable="false"
          show-icon
          style="margin-top: 20px;"
        />
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getProcessById } from '@/api/process'
import { startProcess } from '@/api/approval'

export default {
  name: 'ApprovalStart',
  
  data() {
    return {
      process: {},
      formFields: [],
      approvalForm: {
        processId: null,
        title: '',
        formData: {}
      },
      approvalRules: {
        title: [
          { required: true, message: '请输入审批标题', trigger: 'blur' }
        ]
      },
      submitting: false,
      hasPermission: true,
      permissionMessage: ''
    }
  },
  
  created() {
    this.loadProcess()
  },
  
  methods: {
    loadProcess() {
      const processId = this.$route.params.id
      this.approvalForm.processId = parseInt(processId)
      
      getProcessById(processId).then(res => {
        this.process = res.data
        
        // 解析表单配置（支持表单设计器生成的配置）
        if (res.data.formConfig) {
          try {
            const formItems = JSON.parse(res.data.formConfig)
            
            // 转换表单设计器的配置为字段列表
            if (Array.isArray(formItems)) {
              this.formFields = formItems.map(item => ({
                name: item.key,
                label: item.label,
                type: item.type,
                placeholder: item.placeholder || `请输入${item.label}`,
                required: item.required || false,
                options: item.options || [],
                rows: item.rows || 3,
                min: item.min,
                max: item.max,
                step: item.step,
                defaultValue: item.defaultValue
              }))
              
              // 初始化表单数据
              this.formFields.forEach(field => {
                const defaultVal = this.getDefaultValue(field)
                this.$set(this.approvalForm.formData, field.name, defaultVal)
              })
            }
          } catch (e) {
            console.error('解析表单配置失败', e)
            this.$message.error('表单配置解析失败')
          }
        } else {
          this.$message.warning('该流程未配置表单')
        }
      }).catch(error => {
        console.error('加载流程失败:', error)
      })
    },
    
    // 获取字段默认值
    getDefaultValue(field) {
      if (field.defaultValue !== undefined && field.defaultValue !== '') {
        return field.defaultValue
      }
      
      switch (field.type) {
        case 'number':
          return 0
        case 'checkbox':
          return []
        case 'switch':
          return false
        case 'rate':
          return 0
        case 'slider':
          return field.min || 0
        default:
          return ''
      }
    },
    
    handleSubmit() {
      this.$refs.approvalForm.validate(valid => {
        if (valid) {
          this.submitting = true
          startProcess(this.approvalForm)
            .then(() => {
              this.$message.success('提交成功')
              this.$router.push({
                path: '/approval-center',
                query: { tab: 'applications' }
              })
            })
            .catch(() => {
              this.submitting = false
            })
            .finally(() => {
              this.submitting = false
            })
        }
      })
    }
  }
}
</script>

<style scoped>
.approval-start-container {
  max-width: 800px;
}
</style>

